<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">

      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-form label-width="70px" size="small" v-formkey="{query:crud.toQuery}">
          <el-row :gutter="10">
            <el-col :span="12" :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="业务日期">
                <div class="flex flex-row">
                  <el-date-picker
                    v-model="query.startTime"
                    align="right"
                    unlink-panels
                    class="fl1"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="开始日期"
                  />
                  <el-date-picker
                    v-model="query.endTime"
                    align="right"
                    unlink-panels
                    class="fl1"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="结束日期"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="方案名称">
                <el-input v-model="query.keyword" placeholder="输入方案名称搜索"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="状态">
                <el-select v-model="query.planStatus" style="width: 150px;">
                  <el-option label="启用" :value="1"></el-option>
                  <el-option label="禁用" :value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <rrOperation :crud="crud"/>
      </div>
      <crudOperation :permission="permission"/>
    </div>
    <div class="body-container">
      <!--表格渲染-->
      <el-table ref="table" stripe border v-loading="crud.loading"
                height="600"
                @row-click="crud.selectRow"
                :row-style="crud.rowClass"
                :row-class-name="crud.tableRowClassName"
                :data="crud.data" size="small" style="width: 100%;"
                @selection-change="crud.selectionChangeHandler">
        <el-table-column :render-header="crud.renderHeader" type="selection" width="60"/>
        <el-table-column :render-header="crud.renderHeader" type="index" width="60" label="序号"/>
        <el-table-column :render-header="crud.renderHeader" prop="busDate" label="业务日期"/>
        <el-table-column :render-header="crud.renderHeader" prop="planName" label="方案名称"/>
        <el-table-column :render-header="crud.renderHeader" prop="planStatus" label="状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.planStatus == 0" type="danger">禁用</el-tag>
            <el-tag v-else type="success">启用</el-tag>
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" prop="createTime" label="添加时间"/>
        <el-table-column :render-header="crud.renderHeader" prop="enableUserName" label="启用人"/>
        <el-table-column :render-header="crud.renderHeader" prop="enableDate" label="启用时间"/>
        <el-table-column :render-header="crud.renderHeader" prop="disableUserName" label="禁用人"/>
        <el-table-column :render-header="crud.renderHeader" prop="disableDate" label="禁用时间"/>
        <el-table-column :render-header="crud.renderHeader" prop="createUserName" label="创建人"/>
        <el-table-column :render-header="crud.renderHeader" v-permission="['admin','basGoods:edit','basGoods:del']"
                         label="操作" width="150px"
                         align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination/>
    </div>

    <!-- 新增工资计划弹窗 -->
    <el-dialog :before-close="crud.cancelCU" :close-on-click-modal="false" :title="crud.status.title"
               :visible.sync="crud.status.cu > 0" append-to-body width="80%">
      <div>
        <el-form ref="form" :inline="true" :model="form" :rules="rules" label-width="80px" size="small">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="方案名称" prop="planName">
                <el-input placeholder="请输入方案名称" v-model="form.planName" clearable style="width: 150px;"/>
              </el-form-item>
              <el-form-item label="业务日期" prop="planName">
                <el-date-picker
                  v-model="form.busDate"
                  type="date"
                  style="width: 100%;"
                  format="yyyy - MM - dd "
                  value-format="yyyy-MM-dd"
                  default-value
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="方案状态" prop="planStatus">
                <el-select v-model="form.planStatus" clearable style="width: 150px;">
                  <el-option label="禁用" :value="0"></el-option>
                  <el-option label="启用" :value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="多配送员是否平分" prop="avgFlag" label-width="110px">
                <el-select v-model="form.avgFlag" clearable style="width: 150px;">
                  <el-option label="是" :value="0"></el-option>
                  <el-option label="否" :value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="提成规则" prop="payRule">
                <el-select v-model="form.payRule" clearable  style="width: 150px;">
                  <el-option label="固定" :value="0"></el-option>
                  <el-option label="阶梯" :value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="提成单据" prop="payBill">
                <el-select v-model="form.payBill" clearable style="width: 150px;">
                  <el-option label="按已核销单据" :value="0"></el-option>
                  <el-option label="按开单" :value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="时间维度" prop="payTime">
                <el-select v-model="form.payTime" clearable style="width: 180px;">
                  <el-option label="按核销时间" :value="0"></el-option>
                  <el-option label="按开单" :value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="提现方法" prop="payWay">
                <el-radio-group v-model="form.payWay" style="width: 400px;" @change="onPayWay">
                  <el-radio :label="0">按销售额</el-radio>
                  <el-radio :label="1">按毛利</el-radio>
                  <el-radio :label="2">按数量</el-radio>
                  <el-radio :label="3">按箱数</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <div style="margin-left: 20px">
              <el-button @click="removeGoods">剔除商品</el-button>
            </div>
            <el-col :span="8" style="margin-top: 20px">
              <el-card class="box-card" style="min-height: 30vh;position: relative">
                <el-tabs v-model="tabsActiveName" @tab-click="tablesHandleClick"
                         style="width: 100%">
                  <el-tab-pane name="goodBrand" label="按品牌">
                    <div class="el_table">
                      <el-table @row-click="brandSelect"
                                :show-header="false"
                                :data="goodBrands"
                                style="width: 100%" height="300">
                        <el-table-column prop="name" label="名称"></el-table-column>
                        <el-table-column>
                          <template slot-scope="scope">
                            <el-input @input="changeBrandRate(scope.$index,scope.row,$event)"
                                      type="number" :min="0" :max="100" style="width: 100%"
                                      v-model="scope.row.payRate" placeholder="输入提成比例"/>
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>

                  </el-tab-pane>
                  <el-tab-pane name="goodType" label="按分类">
                    <div class="el_table">
                      <el-table @row-click="goodTypeSelect"
                                :show-header="false"
                                :data="goodTypeList"
                                style="width: 100%" height="440">
                        <el-table-column
                          prop="name"
                          label="名称">
                        </el-table-column>
                        <el-table-column>
                          <template slot-scope="scope">
                            <el-input @input="changeGoodsTypeRate(scope.$index,scope.row,$event)" style="width: 100%"
                                      type="number" :min="0" :max="100"
                                      v-model="scope.row.payRate" placeholder="输入提成比例"/>
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                  </el-tab-pane>
                </el-tabs>
              </el-card>
              <el-card v-if="form.payRule" class="box-card" style="min-height: 30vh;position: relative">
                <div>
                  <div class="list-topic">
                    <div class="list-topic-item width-four">
                      <span style="color: red">*</span> 区间范围
                    </div>
                    <div class="list-topic-item width-two" style="margin-left: 90px">
                      <span style="color: red">*</span> 提成比例
                    </div>
                  </div>
                  <div class="list-content">
                    <div v-for="(domain, index) in form.paySteps">
                      <div class="list-content-item">
                        <div class="row width-two">
                          <el-input class="input" v-model="domain.startValue" placeholder="开始" clearable></el-input>
                        </div>
                        -
                        <div class="row width-two">
                          <el-input v-model="domain.endValue" placeholder="结束" clearable></el-input>
                        </div>
                        <div class="row width-two" style="margin-left: 10px">
                          <el-input v-model="domain.payRate" placeholder="比例" clearable></el-input>
                        </div>
                        <div class="row width-one">
                          <span
                            style="
                              color: #f56c6c;
                              margin-top: 10px;
                              margin-left: 20px;
                              cursor: pointer;"
                            class="el-icon-remove-outline"
                            @click="removeDomain(domain)"
                          ></span>
                        </div>
                      </div>

                    </div>
                  </div>

                  <el-form-item>
                    <el-button @click="addDomain">新增阶梯</el-button>
                  </el-form-item>
                </div>
              </el-card>
            </el-col>
            <el-col :span="16" style="margin-top: 20px">
              <div>
                <el-form label-width="70px" ref="resetSuggestionQuery" size="small">
                  <el-row :gutter="10">
                    <el-form-item label="商品名称" prop="goodsSuggestionName">
                      <el-input v-model="goodsSuggestionName" clearable
                                placeholder="按商品的名称/编码/条形码搜索"></el-input>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" icon="el-icon-search" @click="goodsSuggestion">搜索</el-button>
                      <el-button icon="el-icon-refresh" @click="resetSuggestionQuery">重置</el-button>
                    </el-form-item>

                  </el-row>
                </el-form>
                <el-table border :data="goodsList" style="width: 100%;margin-top: 20px" height="240">
                  <el-table-column label="商品编码" prop="code"></el-table-column>
                  <el-table-column label="商品名称" prop="name"></el-table-column>
                  <el-table-column label="条形码" prop="barcode"></el-table-column>
                  <el-table-column label="商品品牌" prop="goodsBrandName"></el-table-column>
                  <el-table-column label="商品分类" prop="goodsTypeName"></el-table-column>
                  <el-table-column label="提成比例" fixed="right" align="center" width='170px'>
                    <template slot-scope="scope">
                      <el-input @input="changeGoodsRate(scope.$index,scope.row,$event)"
                                type="number" :min="0" :max="100" style="width: 100%;padding: 0 10px; "
                                v-model="scope.row.payRate" placeholder="输入提成比例"/>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div style="margin-top: 20px">
                <div>剔除商品</div>
                <el-table border :data="form.removeGoodsListSelected" height="200" style="width: 100%">
                  <el-table-column label="商品编码" prop="code"></el-table-column>
                  <el-table-column label="商品名称" prop="name"></el-table-column>
                  <el-table-column label="条形码" prop="barcode"></el-table-column>
                  <el-table-column label="商品品牌" prop="goodsBrandName"></el-table-column>
                  <el-table-column label="商品分类" prop="goodsTypeName"></el-table-column>
                  <el-table-column label="操作" fixed="right" width="200px" align="center">
                    <template slot-scope="{$index}">
                      <el-button type="text"  @click="delDetailgoods($index)" size="small">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div style="margin-top: 20px">
                <div>
                  <el-form-item label="客户类型" prop="customerType">
                    <el-select v-model="form.customerClassify" class="edit-input" clearable
                               placeholder="请选择客户类型"
                               @change="changeCustomerClassify"
                               style="width: 100%;">
                      <el-option
                        v-for="(item,index) in customerClassifyList"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="客户类型名称" prop="customerTypeName" label-width="100px">
                    <treeselect v-if="form.customerClassify===1" v-model="form.customerTypeIds"
                                :multiple="true"
                                :normalizer="normalizer" style="width: 310px;"
                                :options="customerTypeTreeList" placeholder="请选择客户分类名称"/>
                    <treeselect v-else-if="form.customerClassify===2" v-model="form.customerAreaIds"
                                :multiple="true"
                                :normalizer="normalizer" style="width: 310px;"
                                :options="customerAreaTreeList" placeholder="请选择客户区域名称"/>
                    <el-select v-else value="" :disabled="form.customerType === 0"></el-select>
                  </el-form-item>
                </div>
                <div style="margin-left: 20px;margin-bottom: 10px">
                  <el-button type="primary" @click="removeCustomer">剔除客户</el-button>
                </div>
                <el-table border :data="form.removeCustomerListSelected" height="200" style="width: 100%">
                  <el-table-column label="客户编码" prop="code"></el-table-column>
                  <el-table-column label="客户名称" prop="name"></el-table-column>
                  <el-table-column label="分类" prop="customerTypeName"></el-table-column>
                  <el-table-column label="区域" prop="customerAreaName"></el-table-column>
                  <el-table-column label="操作" fixed="right" width="200px" align="center">
                    <template slot-scope="{$index}">
                      <el-button type="text"  @click="delDetailcustomer($index)" size="small">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.cu === 2" type="primary" @click="addsub">确认</el-button>
      </div>
    </el-dialog>

    <!-- 剔除例外商品弹窗 -->
    <el-dialog :close-on-click-modal="false" title="剔除商品"
               :visible.sync="removeGoodsDialog" append-to-body width="60%">
      <div style="margin-bottom: 20px">
        <el-form ref="queryGoodsForm" :model="removeGoodsQueryParams" :inline="true" label-width="100px" size="small">
          <el-form-item label="关键字" prop="keyword">
            <el-input v-model="removeGoodsQueryParams.keyword" clearable placeholder="输入关键字搜索"/>
          </el-form-item>
          <el-form-item label="商品品牌" prop="goodsBrandId">
            <zSelect :value.sync="removeGoodsQueryParams.goodsBrandId" url="api/dropDown/basGoodsBrandList"
                     style="width:100%;">
            </zSelect>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="pageGoods">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetGoodsQuery('queryGoodsForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- @selection-change="removeGoodsSelect" -->
      <!--表格渲染-->
      <el-table ref="removeGoodsTable" border
                v-loading="loading"
                @selection-change="crud.selectionChangeHandler"
                :row-key="getRowKeys"
                :data="removeGoodsList">
        <el-table-column type="selection" :reserve-selection="true" width="60"/>
        <el-table-column type="index" width="60" label="序号"/>
        <el-table-column prop="code" label="商品编码"/>
        <el-table-column prop="name" label="商品名称"/>
        <el-table-column prop="barcode" label="条形码"/>
        <el-table-column prop="goodsBrandName" label="商品品牌"/>
        <el-table-column prop="goodsTypeName" label="商品分类"/>
      </el-table>
      <!--分页组件-->
      <el-pagination
        :current-page.sync="removeGoodsQueryParams.page"
        :page-size.sync="removeGoodsQueryParams.size"
        :total="total"
        :page-sizes="[10, 20, 30, 40, 50, 100, 500 ,1000]"
        style="margin-top: 8px; bottom:35px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="removeGoodsDialog=false">取消</el-button>
        <el-button  type="primary" @click="submitCU">确认</el-button>
      </div>
    </el-dialog>
    <!-- 剔除例外客户弹窗 -->
    <el-dialog :close-on-click-modal="false" title="剔除客户"
               :visible.sync="removeCustomerDialog" append-to-body width="60%">
      <div style="margin-bottom: 20px">
        <el-form ref="removeCustomerQueryParams" :model="removeCustomerQueryParams" :inline="true" label-width="100px"
                 size="small">
          <el-form-item label="关键字" prop="keyword">
            <el-input v-model="removeCustomerQueryParams.keyword" clearable placeholder="输入关键字搜索"/>
          </el-form-item>
          <el-form-item label="客户分类" prop="type">
            <el-select v-model="removeCustomerQueryParams.type" class="edit-input" clearable placeholder="请选择"
                       style="width: 100%;">
              <el-option
                v-for="(item,index) in dict.t_bas_customer_type"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="pageCustomer">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetCustomerQuery('removeCustomerQueryParams')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!--表格渲染-->
      <el-table ref="removeCustomerTable" border
                v-loading="customerLoading"
                @selection-change="crud.selectionChangeHandler"
                :row-key="getRowKeys"
                :data="removeCustomerList">
        <el-table-column type="selection" :reserve-selection="true" width="60"/>
        <el-table-column type="index" width="60" label="序号"/>
        <el-table-column label="客户编码" prop="code"></el-table-column>
        <el-table-column label="客户名称" prop="name"></el-table-column>
        <el-table-column label="分类" prop="customerTypeName"></el-table-column>
        <el-table-column label="区域" prop="customerAreaName"></el-table-column>
      </el-table>
      <!--分页组件-->
      <el-pagination
        :current-page.sync="removeCustomerQueryParams.page"
        :page-size.sync="removeCustomerQueryParams.size"
        :total="customerTotal"
        :page-sizes="[10, 20, 30, 40, 50, 100, 500 ,1000]"
        style="margin-top: 8px; bottom:35px"
        @size-change="handleCustomerSizeChange"
        @current-change="handleCustomerCurrentChange"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="removeCustomerDialog=false">取消</el-button>
        <el-button  type="primary" @click="submitCU1">确认</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {getCustomerAreaTree} from '@/api/erp/basCustomerArea'
import {getCustomerTypeTree} from '@/api/erp/basCustomerType'
import Treeselect from '@riophae/vue-treeselect'
import {get as getGoods} from '@/api/erp/basGoods'
import {get as getCustomer} from '@/api/erp/basCustomer'
import CRUD, {crud, form, header, presenter} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import crudBasSolution from '@/api/erp/salarySolution';
import {getById, getPlanBrand, getPlanGoodsType, listGoodsByBrandId, listGoodsByTypeId} from '@/api/erp/salarySolution'


// crud交由presenter持有
const defaultCrud = CRUD({
  title: '工资方案', url: '/api/payPlan', sort: 'id,desc', crudMethod: {...crudBasSolution}, optShow: {
    add: true,
    edit: true,
    del: true,
    download: false,
    leadingIn: false,
    enable: true,
    disable: true,
  },
  props: {
    tableColumns: [
      'name',
      'code'
    ]
  }
});
const defaultForm = {
  planName: null,
  busDate: null,
  planStatus: null,
  // 多配送员是否平
  avgFlag: null,
  //提成规则
  payRule: null,
  //提成单据
  payBill: null,
  //时间维度
  payTime: null,
  //提成方法
  payWay: null,
  // 按品牌分配比例的对象，key：brandId，value:payRate
  brandPayRate: {},
  // 按商品类型分配比例的对象，key：typeId，value:payRate
  goodsTypePayRate: {},
  //单独设置商品比例的商品集合，key为商品code，value为比例
  goodsListMap: {},
  paySteps: [
    // {
    //   startValue: null,
    //   endValue: null,
    //   payRate: null
    // }
  ],
  // 选中的例外商品
  removeGoodsListSelected: [],
  // 选中的例外客户
  removeCustomerListSelected: [],

  // 选中的客户类型
  customerClassify: 0,
  // 客户类型id集合
  customerTypeIds: [],
  // 客户区域id集合
  customerAreaIds: [],
}
export default {
  name: "index",
  components: {pagination, crudOperation, rrOperation, udOperation, Treeselect},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  dicts: ['t_bas_customer_type'],
  data() {
    return {
      payPlanId:null,
      permission: {
        //add 不添加权限，这个add按钮自定义
        add: ['admin'],
        edit: ['admin', 'basGoods:edit'],
        del: ['admin', 'basGoods:del'],
        enable: ['admin', 'basGoods:enable'],
        disable: ['admin', 'basGoods:disable'],
      },
      rules: {
        planName: [{required: true, message: '方案名称不能为空', trigger: 'blur'}],
        busDate: [{required: true, message: '业务日期不能为空', trigger: 'blur'}],
        planStatus: [{required: true, message: '方案状态不能为空', trigger: 'blur'}],
        avgFlag: [{required: true, message: '平分方式不能为空', trigger: 'blur'}],
        payRule: [{required: true, message: '提成规则不能为空', trigger: 'blur'}],
        payBill: [{required: true, message: '提成单据不能为空', trigger: 'blur'}],
        payTime: [{required: true, message: '时间维度不能为空', trigger: 'blur'}],
        payWay: [{required: true, message: '提成方法不能为空', trigger: 'blur'}],
      },
      tabsActiveName: 'goodBrand',
      goodBrands: [],
      goodTypeList: [],
      goodsList: [],
      oldGoodsList: [],
      brandAndType: false,
      planId: null,
      goodsSuggestionName: '',
      // 剔除商品弹窗
      removeGoodsDialog: false,
      removeGoodsList: [],
      // 查询参数
      removeGoodsQueryParams: {
        page: 1,
        size: 10,
        keyword: null,
        goodsBrandId: null,
      },
      total: 0,
      loading: true,
      // 剔除客户弹窗
      removeCustomerDialog: false,
      // 查询参数
      removeCustomerQueryParams: {
        page: 1,
        size: 10,
        keyword: null,
        type: null
      },
      customerLoading: true,
      removeCustomerList: [],
      customerTotal: 0,
      customerTypeTreeList: [],
      customerAreaTreeList: [],
      // 客户类型-选择
      customerClassifyList: [{
        label: '全体客户',
        value: 0
      }, {
        label: '客户分类',
        value: 1
      }, {
        label: '客户区域',
        value: 2
      }],
      extendRightEvent:[
        {
          fnHandler: 'delDetail', // 绑定事件
          icoName: 'el-icon-delete', // icon图标
          btnName: '删除' // 菜单名称
        },
      ],
    }
  },
  created() {
    // console.log("===", this.crud.from)

  },
  watch: {
    'crud.status.cu': {
      handler(n, o) {
        console.log("监听", n)
        if (n === 1) {
          this.listPlanBrand();
          this.listPlanGoodsType();
        } else {
          this.goodBrands = [];
          this.goodTypeList = [];
          this.goodsList = [];
          this.form.removeGoodsListSelected = [];
          this.form.removeCustomerListSelected = [];
          this.goodsSuggestionName=''
        }
      }
    },
    if (condition) {
      
    }
  },
  methods: {
    addsub(){
      if (this.crud.status.add) {
        let planNames=this.crud.data.map((item)=>{
        return item.planName
      })
      if (planNames.includes(this.form.planName)) {
          this.$message('方案名称不能重复');
        }else{
          this.crud.submitCU()
        }
      }else{
        this.crud.submitCU()
      }
      
    },
    delDetailgoods(index){
      this.form.removeGoodsListSelected.splice(index,1)
      this.crud.selectionChangeHandler(this.form.removeGoodsListSelected)
      this.changeGoodsSelected()
    },
    delDetailcustomer(index){
      this.form.removeCustomerListSelected.splice(index,1)
      this.crud.selectionChangeHandler(this.form.removeCustomerListSelected)
      this.changeCustomerSelected()
    },
    submitCU(){
      this.removeGoodsDialog=false;
      this.form.removeGoodsListSelected=this.crud.selections
      console.log(this.crud.selections)
    },
    submitCU1(){
      this.removeCustomerDialog=false;
      this.form.removeCustomerListSelected=this.crud.selections
      console.log(this.crud.selections,'0')
    },
    changeCustomerClassify() {
      let type = this.form.customerClassify
      console.log("客户类型", type)
      if (type === 1) {
        this.listCustomerTypeTree()
      } else if (type === 2) {
        this.listCustomerAreaTree()
      }
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    //获取客户区域树型数据
    listCustomerAreaTree() {
      getCustomerAreaTree().then(res => {
        this.customerAreaTreeList = res.data
      })
    },
    //获取客户类型树型数据
    listCustomerTypeTree() {
      getCustomerTypeTree().then(res => {
        this.customerTypeTreeList = res
      })
    },
    // 剔除客户弹窗
    removeCustomer() {
      this.removeCustomerDialog = true
      this.pageCustomer()
    },
    // 分页查询客户列表
    pageCustomer() {
      this.customerLoading = true
      getCustomer(this.removeCustomerQueryParams).then(res => {
        // console.log("客户列表", res)
        this.removeCustomerList = res.data.content
        this.customerTotal = res.data.totalElements
        this.customerLoading = false
      })
    },
    // 选中例外客户
    removeCustomerSelect(val) {
      // console.log("选中客户===", val)
      this.form.removeCustomerListSelected = val
    },
    // 选中剔除商品
    removeGoodsSelect(val) {
      // console.log("选中商品===", val)
      this.form.removeGoodsListSelected = val
    },
    // 重置剔除客户输入条件
    resetCustomerQuery(queryForm) {
      /** 重置按钮操作 */
      this.$refs[queryForm].resetFields()
      this.pageCustomer();
    },
    handleSizeChange(val) {
      if (this.removeGoodsQueryParams.page * val > this.total) {
        this.removeGoodsQueryParams.page = 1
        this.removeGoodsQueryParams.size = 0
      }
    },
    // 下一页
    handleCurrentChange(val) {
      this.removeGoodsQueryParams.page = val
      this.pageGoods()
    },

    handleCustomerSizeChange(val) {
      if (this.removeCustomerQueryParams.page * val > this.total) {
        this.removeCustomerQueryParams.page = 1
        this.removeCustomerQueryParams.size = 0
      }
    },
    // 下一页
    handleCustomerCurrentChange(val) {
      this.removeCustomerQueryParams.page = val
      this.pageCustomer()
    },

    // 回显选中数据
    changeGoodsSelected() {
        this.$nextTick(function () {
          this.$refs.removeGoodsTable.clearSelection()
          const removeGoodsList = this.form.removeGoodsListSelected.map(item=>item.code)
          this.removeGoodsList.forEach(item=>{
            if(removeGoodsList.includes(item.code))
            this.$refs.removeGoodsTable.toggleRowSelection(item, true)
          })
          // this.form.removeGoodsListSelected.forEach(goods => {
          //   this.removeGoodsList.forEach(item => {
          //     if (item.code === goods.code) {
          //       this.$refs.removeGoodsTable.toggleRowSelection(item, true)
          //     }
          //   })
          // })
        })
    },
    changeCustomerSelected() {
        this.$nextTick(function () {
          this.$refs.removeCustomerTable.clearSelection()
          const removeCustomerList = this.form.removeCustomerListSelected.map(item=>item.code)
          this.removeCustomerList.forEach(item=>{
            if(removeCustomerList.includes(item.code))
            this.$refs.removeCustomerTable.toggleRowSelection(item, true)
          })
        })
    },
    // 回显已经选中的项
    getRowKeys(row) {
      return row.code; //一般是你选择项的id
    },
    // 剔除商品弹窗
    removeGoods() {
      this.removeGoodsDialog = true
      this.pageGoods()
    },
    // 查询商品列表
    pageGoods() {
      this.loading = true
      getGoods(this.removeGoodsQueryParams).then(res => {
        this.removeGoodsList = res.data.content
        this.total = res.data.totalElements
        this.loading = false
        console.log("接口返回商品", this.removeGoodsList)
        console.log("选中的商品", this.form.removeGoodsListSelected)
        this.changeGoodsSelected()
      })
    },
    // 重置剔除商品输入条件
    resetGoodsQuery(queryGoodsForm) {
      /** 重置按钮操作 */
      this.$refs[queryGoodsForm].resetFields()
      this.pageGoods();
    },
    // 删除输入框
    removeDomain(item) {
      var index = this.form.paySteps.indexOf(item);
      if (index !== -1) {
        this.form.paySteps.splice(index, 1);
      }
    },
    // 添加输入框
    addDomain() {
      this.form.paySteps.push({
        startValue: null,
        endValue: null,
        payRate: null,
        key: Date.now()
      });
      console.log("当前", this.form.paySteps)
    },
    // 切换修改规则事件
    // changePayRule() {
    //   console.log('提成规则', this.form.payRule)
    //   if (this.form.payRule === 1) {
    //     this.brandAndType = true
    //   } else {
    //     this.brandAndType = false
    //   }
    // },
    onPayWay() {
      console.log('体现方法', this.form.payWay)
    },
    // 切换按品牌或者分类
    tablesHandleClick(tab, event) {
      let name = tab.name;
      if (name === 'goodBrand') {
        this.listPlanBrand()
      } else if (name === 'goodType') {
        this.listPlanGoodsType()
      }
    },
    // 查询所有品牌
    listPlanBrand() {
      if (this.goodBrands.length > 0) {
        return
      }
      let params = {
        size: 10000,
        planId: this.planId
      }
      getPlanBrand(params).then(res => {
        this.goodBrands = res.data.content
      })  
    },
    // 查询所有商品分类
    listPlanGoodsType() {
      if (this.goodTypeList.length > 0) {
        return
      }
      let params = {
        size: 10000,
        planId: this.planId
      }
      getPlanGoodsType(params).then(res => {
        this.goodTypeList = res.data.content
      })
    },
    // 选中品牌
    brandSelect(row) {
      console.log("品牌row", row)
      this.goodsList = []
      let param = {
        brandId: row.brandId,
         payPlanId:this.payPlanId
      }
      listGoodsByBrandId(param).then(res => {
        console.log("根据品牌查询商品结果", res)
        res.data.forEach(item => {
          let payRate = this.form.goodsListMap[item.goodsId];
          if (payRate) {
            item.payRate = payRate
          }
          this.goodsList.push(item)
        })
        this.oldGoodsList = this.goodsList
      })
    },
    goodsSuggestion() {
      // console.log("关键词", this.goodsSuggestionName,this.goodsList,'0000',this.oldGoodsList)
      // this.goodsList.forEach(goods => {
      //   console.log('///',goods)
      //   if (goods.name.indexOf(this.goodsSuggestionName) === 0) {
      //     _goodsList.push(goods)
      //   }
      // })
      let _goodsList = [];
      let obj = {};
      this.oldGoodsList.map(item=>{
        if(item.code.includes(this.goodsSuggestionName)||item.name.includes(this.goodsSuggestionName)||item.barcode.includes(this.goodsSuggestionName)){
          _goodsList.push(item)
        }
      })
      this.goodsList = _goodsList.reduce(function(item, next) {
       obj[next.code] ? '' : obj[next.code] = true && item.push(next);
       return item;
    }, []);
    this.goodsList = _goodsList
      // console.log("筛选后的商品", this.goodsList)
    },
    resetSuggestionQuery() {
      this.goodsSuggestionName = ''
      this.goodsList = this.oldGoodsList
    },
    // 选中分类
    goodTypeSelect(row) {
      console.log("品牌分类row", row)
      this.goodsList = []
      let param = {
        typeId: row.typeId,
         payPlanId:this.payPlanId
      }
      listGoodsByTypeId(param).then(res => {
        console.log("根据品牌分类商品结果", res)
        res.data.forEach(item => {
          let payRate = this.form.goodsListMap[item.goodsId];
          if (payRate) {
            item.payRate = payRate
          }
          this.goodsList.push(item)
        })
        this.oldGoodsList = this.goodsList
      })
    },
    // 修改品牌下商品比例
    changeBrandRate(index, row, event) {

      this.$set(this.form.brandPayRate, row.brandId, row.payRate)
      this.goodsList.forEach(goods => {
        goods.payRate = row.payRate
        this.$set(this.form.goodsListMap, goods.goodsId, row.payRate)
      })
    },
    // 修改商品分类下商品比例
    changeGoodsTypeRate(index, row, event) {
      this.$set(this.form.goodsTypePayRate, row.typeId, row.payRate)

      this.goodsList.forEach(goods => {
        goods.payRate = row.payRate
        this.$set(this.form.goodsListMap, goods.goodsId, row.payRate)
      })
    },
    //修改商品提成比例
    changeGoodsRate(index, row, event) {
      this.$set(this.form.goodsListMap, row.goodsId, row.payRate)
      
    },
    // 打开编辑弹窗前做的操作
    [CRUD.HOOK.beforeToEdit](crud, form) {
      
      this.planId = form.id;
      this.getPlanById(form.id)
      this.listCustomerTypeTree()
      this.listCustomerAreaTree()
    },
    getPlanById(id) {
      getById(id).then(res => {
         this.payPlanId=res.id
        this.form.brandPayRate = res.brandPayRate
        this.form.goodsListMap = res.goodsListMap
        this.form.goodsTypePayRate = res.goodsTypePayRate
        this.form.paySteps = res.paySteps
        this.form.removeCustomerListSelected = res.removeCustomerListSelected
        this.form.removeGoodsListSelected = res.removeGoodsListSelected
        this.form.customerClassify = res.customerClassify
        if (res.customerClassify === 1) {
          res.customerClassifyList.forEach(item => {
            this.form.customerTypeIds.push(item.customerTypeId)
          })
        } else if (res.customerClassify === 2) {
          res.customerClassifyList.forEach(item => {
            this.form.customerAreaIds.push(item.customerAreaId)
          })
        }
        console.log("根据计划id查询计划详情", res)
        console.log("赋值后", this.form)
      })
    }
  }
}
</script>

<style scoped>
/* 去除表格线 */
.el_table >>> .el-table__row > td {
  border: none;
}

/* 去除上边框 */
.el_table >>> .el-table th.is-leaf {
  border: none;
}

/* 去除下边框 */
.el_table >>> .el-table::before {
  height: 0;
}

.list-topic {
  height: 40px;
  background-color: #f5f7fa;
  display: flex;
  line-height: 40px;
}

.list-topic-item {
  font-size: 14px;
  color: #8e8ea1;
}

.width-one {
  text-align: center;
  width: 15%;
}

.width-two {
  width: 27%;
}

.width-three {
  width: 27%;
  margin-right: 10px;
}

.width-four {
  margin-right: 10px;
  width: 27%;
}

.list-content {
  overflow: auto;
}

.list-content-item {
  height: 32px;
  line-height: 32px;
  padding: 8px 0px;
  box-sizing: content-box;
  display: flex;
}

</style>
